# -*- coding: utf-8 -*-
"""
Web framework/Tornado WebSocket/test02/WebSocket Client.py
"""
import tornado.websocket
import tornado.web
import asyncio
import tornado.ioloop
from tornado import gen
from apscheduler.schedulers.tornado import TornadoScheduler

websocket_connect = None


class IndexHandler(tornado.web.RequestHandler):
    global websocket_connect

    def get(self):
        """
        tornado.websocket.WebSocketClientConnection.write_message
        :return:
        """
        websocket_connect.write_message("I'm Client, Say Hello.")
        self.finish()

    def post(self):
        """
        tornado.websocket.WebSocketClientConnection.close
        :return:
        """
        websocket_connect.close()
        self.finish()


class WebSocketCon(object):

    def __init__(self, url):
        self.url = url
        self.connect()

    @gen.coroutine
    def connect(self):
        """
        tornado.websocket.websocket_connect
        :return:
        """
        global websocket_connect
        print("WebSocketCon.connect Start.")
        try:
            websocket_connect = yield tornado.websocket.websocket_connect(
                url=self.url
            )
            self.websocket_connect = websocket_connect
        except Exception as e:
            print(e)
        else:
            self.read_message()

    @gen.coroutine
    def read_message(self):
        """
        tornado.websocket.WebSocketClientConnection.read_message
        :return:
        """
        print("WebSocketCon.read_message Start.")
        while True:
            if self.websocket_connect:
                message = yield self.websocket_connect.read_message()
                if message is not None:
                    print(message)
            else:
                break

    def ping_server(self, websocket_client):
        """
        tornado.websocket.WebSocketClientConnection.ping
        :param websocket_client:
        :return:
        """
        print("WebSocketCon.ping_server Start.")
        new_loop = asyncio.new_event_loop()
        asyncio.set_event_loop(new_loop)
        if websocket_client:
            websocket_client.ping("ping")


async def main():
    global websocket_connect
    websocket_client = WebSocketCon(url="ws://127.0.0.1:8888/websocket/")
    tsch = TornadoScheduler()
    tsch.add_job(lambda: websocket_client.ping_server(websocket_client.websocket_connect), trigger='interval',
                 seconds=2)
    tsch.start()
    app = tornado.web.Application([
        (r"/", IndexHandler)
    ])
    app.listen(7777)
    await asyncio.Event().wait()


if __name__ == '__main__':
    asyncio.run(main())
